package club.gongsir.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 龚涛
 * @date 2020/6/22 21:28
 * 编码不要畏惧变化，要拥抱变化
 */
public class Ranking extends Configured implements Tool {

    /**
     * 日志工具
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public int run(String[] args) throws Exception {
        // 创建作业，配置作业所需参数
        Configuration conf = new Configuration();

        // 创建作业
        Job job = Job.getInstance(conf,"Ranking");
        // 输入, 输出
        String inPath = args[0], outPath = args[1];
        logger.info("=====>> inPath = {}",inPath);
        logger.info("=====>> outPath = {}",outPath);
        // 注入作业的主类
        job.setJarByClass(Ranking.class);

        // 为作业注入Map和Reduce类
        job.setMapperClass(Map.class);
        // 自定义分组
        job.setGroupingComparatorClass(Grouping.class);
        job.setReducerClass(Reduce.class);

        // 指定输入类型为：文本格式文件；注入文本输入格式类
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job, new Path(inPath));

        // 指定输出格式为：文本格式文件；注入文本输入格式类
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setOutputKeyClass(RatingTuple.class);
        job.setOutputValueClass(Text.class);
        // 指定作业的输出目录
        TextOutputFormat.setOutputPath(job, new Path(outPath));
        // 作业的执行流程
        // 执行MapReduce
        return job.waitForCompletion(true) ? 0 : 1;
    }

    private static class Map extends Mapper<LongWritable, Text, RatingTuple, Text> {
        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            if (line.contains("Unrated")){
                return;
            }
            // 制表符分割数据
            String[] items = line.split("\\t");
            if (items.length == 6) {
                RatingTuple tuple = new RatingTuple();
                // 国家(地区)
                tuple.setCity(new Text(items[4]));
                // stars 分数
                tuple.setScore(new FloatWritable(Float.parseFloat(items[5])));
                context.write(tuple,new Text(items[1]));
                System.out.println("key: " + items[4] + " line: " + line);
            }
        }
    }

    private static class Reduce extends Reducer<RatingTuple, Text, Text, Text> {
        @Override
        public void reduce(RatingTuple key, Iterable<Text> val, Context context) throws IOException, InterruptedException {
            try {
                Iterator<Text> values = val.iterator();
                List<String> list = new ArrayList<>();
                List<String> brands = new ArrayList<>();

                while (values.hasNext())  {
                    String star = key.getScore().toString();
                    String brand = values.next().toString();
                    String str = "brand:" + brand + "," + "star:" + star;
                    // 去重
                    if (brands.size() < 3 && !list.contains(str)) {
                        list.add(str);
                        brands.add(brand);
                    } else if (brands.size() == 3) {
                        break;
                    }
                }
                if (brands.size() == 3) {
                    context.write(new Text(key.getCity().toString()+"\t")
                            ,new Text(String.join("\t",list)));
                }
            } catch (Exception ex) {
                System.out.println("Error " + key.toString());
                System.out.println(ex.getMessage());
            }
        }
    }

    private static class Grouping extends WritableComparator {
        protected Grouping() {
            super(RatingTuple.class,true);
        }

        @Override
        public int compare(WritableComparable a, WritableComparable b) {
            RatingTuple k1 = (RatingTuple) a;
            RatingTuple k2 = (RatingTuple) b;
            return k1.getCity().compareTo(k2.getCity());
        }
    }
}
